<template>
  <div class="register-container">
    <div class="register-wrapper">
      <!-- 左侧背景 -->
      <div class="register-bg">
        <div class="bg-content">
          <h1 class="bg-title">加入我们</h1>
          <p class="bg-subtitle">开启您的学习之旅</p>
          <div class="bg-steps">
            <div class="step-item">
              <div class="step-number">1</div>
              <div class="step-content">
                <h4>注册账号</h4>
                <p>填写基本信息</p>
              </div>
            </div>
            <div class="step-item">
              <div class="step-number">2</div>
              <div class="step-content">
                <h4>选择课程</h4>
                <p>浏览感兴趣的课程</p>
              </div>
            </div>
            <div class="step-item">
              <div class="step-number">3</div>
              <div class="step-content">
                <h4>开始学习</h4>
                <p>享受学习的乐趣</p>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 右侧注册表单 -->
      <div class="register-form-wrapper">
        <div class="register-form">
          <div class="form-header">
            <h2 class="form-title">学生注册</h2>
            <p class="form-subtitle">请填写您的注册信息</p>
          </div>
          
          <el-steps
            :active="currentStep"
            align-center
            class="register-steps"
            finish-status="success"
          >
            <el-step title="基本信息" />
            <el-step title="验证手机" />
            <el-step title="完成注册" />
          </el-steps>
          
          <!-- 步骤1：基本信息 -->
          <div v-show="currentStep === 0" class="step-content">
            <el-form
              ref="basicFormRef"
              :model="basicForm"
              :rules="basicRules"
              label-width="0"
            >
              <el-form-item prop="username">
                <el-input
                  v-model="basicForm.username"
                  placeholder="请输入用户名"
                  size="large"
                  clearable
                  :prefix-icon="User"
                />
              </el-form-item>
              
              <el-form-item prop="email">
                <el-input
                  v-model="basicForm.email"
                  placeholder="请输入邮箱"
                  size="large"
                  clearable
                  :prefix-icon="Message"
                />
              </el-form-item>
              
              <el-form-item prop="password">
                <el-input
                  v-model="basicForm.password"
                  type="password"
                  placeholder="请输入密码"
                  size="large"
                  show-password
                  clearable
                  :prefix-icon="Lock"
                />
              </el-form-item>
              
              <el-form-item prop="confirmPassword">
                <el-input
                  v-model="basicForm.confirmPassword"
                  type="password"
                  placeholder="请确认密码"
                  size="large"
                  show-password
                  clearable
                  :prefix-icon="Lock"
                />
              </el-form-item>
              
              <el-form-item prop="realName">
                <el-input
                  v-model="basicForm.realName"
                  placeholder="请输入真实姓名"
                  size="large"
                  clearable
                  :prefix-icon="UserFilled"
                />
              </el-form-item>
              
              <el-form-item prop="gender">
                <el-select
                  v-model="basicForm.gender"
                  placeholder="请选择性别"
                  size="large"
                  style="width: 100%"
                >
                  <el-option label="男" value="male" />
                  <el-option label="女" value="female" />
                  <el-option label="保密" value="secret" />
                </el-select>
              </el-form-item>
              
              <el-form-item prop="agreement">
                <el-checkbox v-model="basicForm.agreement">
                  我已阅读并同意
                  <el-link type="primary" @click="showAgreement">
                    《用户协议》
                  </el-link>
                  和
                  <el-link type="primary" @click="showPrivacy">
                    《隐私政策》
                  </el-link>
                </el-checkbox>
              </el-form-item>
            </el-form>
          </div>
          
          <!-- 步骤2：验证手机 -->
          <div v-show="currentStep === 1" class="step-content">
            <el-form
              ref="phoneFormRef"
              :model="phoneForm"
              :rules="phoneRules"
              label-width="0"
            >
              <el-form-item prop="phone">
                <el-input
                  v-model="phoneForm.phone"
                  placeholder="请输入手机号"
                  size="large"
                  clearable
                  :prefix-icon="Iphone"
                />
              </el-form-item>
              
              <el-form-item prop="code">
                <div class="sms-wrapper">
                  <el-input
                    v-model="phoneForm.code"
                    placeholder="请输入验证码"
                    size="large"
                    clearable
                    :prefix-icon="Key"
                    class="sms-input"
                  />
                  <el-button
                    size="large"
                    :disabled="smsCountdown > 0 || !phoneForm.phone"
                    :loading="smsLoading"
                    @click="sendSmsCode"
                  >
                    {{ smsCountdown > 0 ? `${smsCountdown}s` : '获取验证码' }}
                  </el-button>
                </div>
              </el-form-item>
            </el-form>
          </div>
          
          <!-- 步骤3：完成注册 -->
          <div v-show="currentStep === 2" class="step-content success-content">
            <div class="success-icon">
              <el-icon size="60" color="var(--success-color)">
                <CircleCheck />
              </el-icon>
            </div>
            <h3 class="success-title">注册成功！</h3>
            <p class="success-subtitle">欢迎加入我们的学习平台</p>
            <div class="success-info">
              <p><strong>用户名：</strong>{{ basicForm.username }}</p>
              <p><strong>邮箱：</strong>{{ basicForm.email }}</p>
              <p><strong>手机号：</strong>{{ phoneForm.phone }}</p>
            </div>
          </div>
          
          <!-- 操作按钮 -->
          <div class="form-actions">
            <el-button
              v-if="currentStep > 0 && currentStep < 2"
              size="large"
              @click="prevStep"
            >
              上一步
            </el-button>
            
            <el-button
              v-if="currentStep < 2"
              type="primary"
              size="large"
              :loading="loading"
              @click="nextStep"
            >
              {{ currentStep === 1 ? '完成注册' : '下一步' }}
            </el-button>
            
            <el-button
              v-if="currentStep === 2"
              type="primary"
              size="large"
              @click="goToLogin"
            >
              立即登录
            </el-button>
          </div>
          
          <div class="form-footer">
            <span>已有账号？</span>
            <el-link type="primary" @click="goToLogin">
              立即登录
            </el-link>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 用户协议对话框 -->
    <el-dialog
      v-model="agreementVisible"
      title="用户协议"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="agreement-content">
        <h4>1. 服务条款</h4>
        <p>欢迎使用我们的在线教育平台。通过注册和使用本服务，您同意遵守以下条款和条件。</p>
        
        <h4>2. 用户责任</h4>
        <p>您有责任保护您的账户信息，包括用户名和密码。您同意不与他人分享您的账户信息。</p>
        
        <h4>3. 内容使用</h4>
        <p>平台上的所有课程内容均受版权保护。您仅可用于个人学习目的，不得用于商业用途。</p>
        
        <h4>4. 服务变更</h4>
        <p>我们保留随时修改或终止服务的权利，恕不另行通知。</p>
        
        <h4>5. 免责声明</h4>
        <p>我们不对因使用本服务而产生的任何直接或间接损失承担责任。</p>
      </div>
      
      <template #footer>
        <el-button @click="agreementVisible = false">关闭</el-button>
      </template>
    </el-dialog>
    
    <!-- 隐私政策对话框 -->
    <el-dialog
      v-model="privacyVisible"
      title="隐私政策"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="privacy-content">
        <h4>1. 信息收集</h4>
        <p>我们收集您提供的个人信息，包括姓名、邮箱、手机号等，用于提供更好的服务。</p>
        
        <h4>2. 信息使用</h4>
        <p>我们使用您的信息来提供服务、改进用户体验、发送重要通知等。</p>
        
        <h4>3. 信息保护</h4>
        <p>我们采用行业标准的安全措施来保护您的个人信息，防止未经授权的访问。</p>
        
        <h4>4. 信息共享</h4>
        <p>除法律要求外，我们不会与第三方分享您的个人信息。</p>
        
        <h4>5. Cookie使用</h4>
        <p>我们使用Cookie来改善用户体验和分析网站使用情况。</p>
      </div>
      
      <template #footer>
        <el-button @click="privacyVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  User,
  UserFilled,
  Lock,
  Message,
  Iphone,
  Key,
  CircleCheck
} from '@element-plus/icons-vue'
import { register, sendSmsCode as apiSendSmsCode, verifySmsCode } from '@/api/auth'

const router = useRouter()

// 表单引用
const basicFormRef = ref()
const phoneFormRef = ref()

// 当前步骤
const currentStep = ref(0)

// 基本信息表单
const basicForm = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  realName: '',
  gender: '',
  agreement: false
})

// 手机验证表单
const phoneForm = reactive({
  phone: '',
  code: ''
})

// 状态数据
const loading = ref(false)
const smsLoading = ref(false)
const smsCountdown = ref(0)
const agreementVisible = ref(false)
const privacyVisible = ref(false)
let smsTimer = null

// 基本信息验证规则
const basicRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
    { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{6,}$/, message: '密码必须包含大小写字母和数字', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== basicForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  agreement: [
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请阅读并同意用户协议和隐私政策'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

// 手机验证规则
const phoneRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码长度为 6 位', trigger: 'blur' }
  ]
}

// 下一步
const nextStep = async () => {
  if (currentStep.value === 0) {
    // 验证基本信息
    if (!basicFormRef.value) return
    
    try {
      const valid = await basicFormRef.value.validate()
      if (!valid) return
      
      currentStep.value = 1
    } catch (error) {
      console.error('表单验证失败:', error)
    }
  } else if (currentStep.value === 1) {
    // 验证手机号并完成注册
    if (!phoneFormRef.value) return
    
    try {
      const valid = await phoneFormRef.value.validate()
      if (!valid) return
      
      loading.value = true
      
      // 验证短信验证码
      await verifySmsCode({
        phone: phoneForm.phone,
        code: phoneForm.code,
        type: 'register'
      })
      
      // 提交注册信息
      await register({
        ...basicForm,
        phone: phoneForm.phone,
        smsCode: phoneForm.code
      })
      
      ElMessage.success('注册成功！')
      currentStep.value = 2
      
    } catch (error) {
      console.error('注册失败:', error)
      ElMessage.error(error.message || '注册失败，请重试')
    } finally {
      loading.value = false
    }
  }
}

// 上一步
const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

// 发送短信验证码
const sendSmsCode = async () => {
  if (!phoneForm.phone) {
    ElMessage.warning('请先输入手机号')
    return
  }
  
  if (!/^1[3-9]\d{9}$/.test(phoneForm.phone)) {
    ElMessage.warning('请输入正确的手机号')
    return
  }
  
  try {
    smsLoading.value = true
    
    await apiSendSmsCode({
      phone: phoneForm.phone,
      type: 'register'
    })
    
    ElMessage.success('验证码已发送')
    
    // 开始倒计时
    smsCountdown.value = 60
    smsTimer = setInterval(() => {
      smsCountdown.value--
      if (smsCountdown.value <= 0) {
        clearInterval(smsTimer)
        smsTimer = null
      }
    }, 1000)
    
  } catch (error) {
    console.error('发送验证码失败:', error)
    ElMessage.error(error.message || '发送验证码失败')
  } finally {
    smsLoading.value = false
  }
}

// 显示用户协议
const showAgreement = () => {
  agreementVisible.value = true
}

// 显示隐私政策
const showPrivacy = () => {
  privacyVisible.value = true
}

// 跳转到登录页
const goToLogin = () => {
  router.push('/auth/login')
}

// 组件卸载
onUnmounted(() => {
  if (smsTimer) {
    clearInterval(smsTimer)
    smsTimer = null
  }
})
</script>

<style lang="scss" scoped>
.register-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: var(--spacing-lg);
}

.register-wrapper {
  width: 100%;
  max-width: 1200px;
  background: var(--bg-color);
  border-radius: 12px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: flex;
  min-height: 700px;
}

.register-bg {
  flex: 1;
  background: linear-gradient(135deg, var(--success-color) 0%, var(--primary-color) 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: var(--spacing-xxxl);
  color: white;
  position: relative;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="50" cy="50" r="1" fill="%23ffffff" opacity="0.1"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>') repeat;
    opacity: 0.3;
  }
}

.bg-content {
  text-align: center;
  position: relative;
  z-index: 1;
}

.bg-title {
  font-size: 2.5rem;
  font-weight: 600;
  margin-bottom: var(--spacing-lg);
  line-height: 1.2;
}

.bg-subtitle {
  font-size: 1.2rem;
  opacity: 0.9;
  margin-bottom: var(--spacing-xxxl);
}

.bg-steps {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xl);
}

.step-item {
  display: flex;
  align-items: center;
  gap: var(--spacing-lg);
  text-align: left;
}

.step-number {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.2rem;
  font-weight: 600;
  flex-shrink: 0;
}

.step-content {
  h4 {
    font-size: 1.1rem;
    margin-bottom: var(--spacing-xs);
  }
  
  p {
    opacity: 0.8;
    font-size: 0.9rem;
  }
}

.register-form-wrapper {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: var(--spacing-xxxl);
}

.register-form {
  width: 100%;
  max-width: 450px;
}

.form-header {
  text-align: center;
  margin-bottom: var(--spacing-xl);
}

.form-title {
  font-size: 1.8rem;
  font-weight: 600;
  color: var(--text-color-primary);
  margin-bottom: var(--spacing-sm);
}

.form-subtitle {
  color: var(--text-color-secondary);
  font-size: var(--font-size-base);
}

.register-steps {
  margin-bottom: var(--spacing-xxxl);
  
  :deep(.el-step__title) {
    font-size: var(--font-size-small);
  }
}

.step-content {
  min-height: 300px;
  
  .el-form-item {
    margin-bottom: var(--spacing-lg);
  }
  
  .el-input,
  .el-select {
    --el-input-height: 48px;
  }
}

.success-content {
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: var(--spacing-xl) 0;
}

.success-icon {
  margin-bottom: var(--spacing-lg);
}

.success-title {
  font-size: 1.5rem;
  font-weight: 600;
  color: var(--success-color);
  margin-bottom: var(--spacing-sm);
}

.success-subtitle {
  color: var(--text-color-secondary);
  margin-bottom: var(--spacing-xl);
}

.success-info {
  background: var(--fill-color-extra-light);
  padding: var(--spacing-lg);
  border-radius: var(--border-radius-base);
  text-align: left;
  
  p {
    margin-bottom: var(--spacing-sm);
    
    &:last-child {
      margin-bottom: 0;
    }
  }
}

.sms-wrapper {
  display: flex;
  gap: var(--spacing-md);
  
  .sms-input {
    flex: 1;
  }
}

.form-actions {
  display: flex;
  gap: var(--spacing-md);
  margin-top: var(--spacing-xxxl);
  margin-bottom: var(--spacing-xl);
  
  .el-button {
    flex: 1;
    height: 48px;
    font-size: var(--font-size-medium);
  }
}

.form-footer {
  text-align: center;
  color: var(--text-color-secondary);
  
  .el-link {
    margin-left: var(--spacing-xs);
  }
}

.agreement-content,
.privacy-content {
  max-height: 400px;
  overflow-y: auto;
  
  h4 {
    color: var(--text-color-primary);
    margin: var(--spacing-lg) 0 var(--spacing-sm) 0;
    
    &:first-child {
      margin-top: 0;
    }
  }
  
  p {
    color: var(--text-color-regular);
    line-height: 1.6;
    margin-bottom: var(--spacing-md);
  }
}

// 响应式设计
@include respond-below(lg) {
  .register-wrapper {
    max-width: 900px;
  }
}

@include respond-below(md) {
  .register-wrapper {
    flex-direction: column;
    max-width: 500px;
  }
  
  .register-bg {
    min-height: 250px;
    padding: var(--spacing-xl);
  }
  
  .bg-title {
    font-size: 2rem;
  }
  
  .bg-steps {
    flex-direction: row;
    justify-content: center;
    gap: var(--spacing-lg);
  }
  
  .step-item {
    flex-direction: column;
    text-align: center;
    gap: var(--spacing-sm);
  }
  
  .step-content {
    h4 {
      font-size: 0.9rem;
    }
    
    p {
      font-size: 0.8rem;
    }
  }
  
  .register-form-wrapper {
    padding: var(--spacing-xl);
  }
  
  .step-content {
    min-height: 250px;
  }
}

@include respond-below(sm) {
  .register-container {
    padding: var(--spacing-md);
  }
  
  .bg-steps {
    flex-direction: column;
    gap: var(--spacing-md);
  }
  
  .step-item {
    flex-direction: row;
    justify-content: flex-start;
  }
  
  .register-form-wrapper {
    padding: var(--spacing-lg);
  }
  
  .form-actions {
    flex-direction: column;
  }
}
</style>